import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../imodel/i_model.dart';

/// 提供数据状态管理widget
class IProviderWidget<T extends IModel> extends StatefulWidget {
  // 构建widgetController
  final Widget Function(BuildContext context, T model)? builder;

  // 数据模型
  final T? model;

  // 是否自动加载初始化数据
  final bool autoInitData;

  IProviderWidget({
    Key? key,
    @required this.builder,
    @required this.model,
    this.autoInitData = true,
  }) : super(key: key);

  IProviderWidgetState<T> createState() => IProviderWidgetState<T>();
}

class IProviderWidgetState<T extends IModel> extends State<IProviderWidget<T>> {
  @override
  void initState() {
    super.initState();
    widget.model?.attachContext(context);
    // 自动加载初始化
    if (widget.autoInitData) {
      widget.model?.requestData();
    }
  }

  @override
  void dispose() {
    widget.model?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T>.value(
      value: widget.model!,
      child: Consumer<T>(
        builder: (context, model, child) {
          var w = widget.builder!(context, model);
          return w;
        },
      ),
    );
  }
}
